import React, {useState, useEffect, useMemo} from 'react';
import { obj_int, d_sort, useCmd, loc, filter_row, BtTxt, PanelFind, uJob, cline, useHigh, GridTable } from 'sui';
import { PsnView } from './psn';

const PickView = () => {
    const [main, setMain] = useState();
    const [inner_num, numInner] = useState();
    const [outer_num, numOuter] = useState();
    const [high] = useHigh(190, 100);
    const umd = useCmd();

    useEffect(() => {
        uJob(null, "pick/count",
            {
                line: cline(),
            },
            r => {
                d_sort(r, "sn");

                let inner = 0;
                let outer = 0;

                r.forEach((d, i) => {
                    d["index"] = i + 1;

                    inner += obj_int(d, "inner");
                    outer += obj_int(d, "outer");
                });

                numInner(inner);
                numOuter(outer);
                setMain(r);
            }, e => setMain(null));
    }, []);

    const getRow = useMemo(() => {
        const lst = ["sn"];
        return filter_row(main, lst, umd.filter);
    }, [main, umd.filter]);

    if (umd.isFin("inner")) {
        return <PsnView cur={umd.cur} hreturn={umd.hreturn} mod="inner" title={loc("l_808")}/>;
    }

    if (umd.isFin("outer")) {
        return <PsnView cur={umd.cur} hreturn={umd.hreturn} mod="outer" title={loc("l_809")}/>;
    }

    const col = [
        {name: loc("l_193"), key: 'index', width: 70},
        {name: loc("l_363"), key: 'sn', width: 200},
        {name: loc("l_238"), key: 'e_opt', width: 180, formatter: (props) => {
            const d = props.row;
            return (
                <div className="inline-flex">
                    <BtTxt hcmd={() => umd.pact(null, d, "inner")}>{loc("l_808")}</BtTxt>
                    <BtTxt hcmd={() => umd.pact(null, d, "outer")}>{loc("l_809")}</BtTxt>
                </div>
            );
        }},
        {name: `${loc("l_808")}${loc("l_127")}`, key: 'inner', width: 100},
        {name: `${loc("l_809")}${loc("l_127")}`, key: 'outer', width: 100},
    ];

    const Left = () => (
        <div className="inline-flex items-center">
            {loc("l_885")}
            <div className="ml-10 bg-teal-300 px-3 pt-2 pb-1">{`${loc("l_808")}${loc("l_127")}`}<span className="ml-6">{inner_num}</span></div>
            <div className="ml-8 bg-teal-300 px-3 pt-2 pb-1">{`${loc("l_809")}${loc("l_127")}`}<span className="ml-6">{outer_num}</span></div>
        </div>
    );

    return (
        <div className="flex flex-col">
            <PanelFind left={<Left/>} hcmd={umd.setFilter}/>
            <GridTable high={high} col={col} row={getRow} rowHeight={45} gref={umd.gref}/>
        </div>
    );
};

export {PickView};
